<?php if (!defined('BASEPATH')) exit('No direct script access allowed.');

/**
 * CodeIgniter URL Helpers
 *
 * @package        CodeIgniter
 * @subpackage    Helpers
 * @category    Helpers
 * @author        Philip Sturgeon
 */

// ------------------------------------------------------------------------

/**
 * Create URL Title - modified version
 *
 * Takes a "title" string as input and creates a
 * human-friendly URL string with either a dash
 * or an underscore as the word separator.
 *
 * Added support for Cyrillic characters.
 *
 * @access    public
 * @param    string    the string
 * @param    string    the separator: dash, or underscore
 * @return    string
 */
if (!function_exists('url_title')) {
    function url_title($str, $separator = 'dash')
    {
        if ($separator == 'dash') {
            $search = '_';
            $replace = '-';
        }
        else
        {
            $search = '-';
            $replace = '_';
        }

        $str = convert_accented_characters_url($str);

        $trans = array(
            $search => $replace,
            "\s+" => $replace,
            "[^a-z0-9" . $replace . "]" => '',
            $replace . "+" => $replace,
            $replace . "$" => '',
            "^" . $replace => ''
        );

        $str = strip_tags(strtolower($str));

        foreach ($trans as $key => $val)
        {
            $str = preg_replace("#" . $key . "#", $val, $str);
        }

        return trim(stripslashes($str));
    }
}

/**
 * Convert Special Chars
 *
 * Found Via:
 * http://us.php.net/manual/en/function.chr.php#72145
 *
 * @access    public
 * @param    string    the string
 * @return    string
 */
function convert_accented_characters_url($string)
{
    $coDau = array("à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ"
    , "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ", "ì", "í", "ị", "ỉ", "ĩ",
                   "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ"
    , "ờ", "ớ", "ợ", "ở", "ỡ",
                   "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
                   "ỳ", "ý", "ỵ", "ỷ", "ỹ",
                   "đ",
                   "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă"
    , "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
                   "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
                   "Ì", "Í", "Ị", "Ỉ", "Ĩ",
                   "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ"
    , "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
                   "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
                   "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
                   "Đ", "ê", "ù", "à");
    $khongDau = array("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"
    , "a", "a", "a", "a", "a", "a",
                      "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
                      "i", "i", "i", "i", "i",
                      "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o"
    , "o", "o", "o", "o", "o",
                      "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
                      "y", "y", "y", "y", "y",
                      "d",
                      "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"
    , "A", "A", "A", "A", "A",
                      "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
                      "I", "I", "I", "I", "I",
                      "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O"
    , "O", "O", "O", "O", "O",
                      "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
                      "Y", "Y", "Y", "Y", "Y",
                      "D", "e", "u", "a");
    return str_replace($coDau, $khongDau, $string);
}


// ------------------------------------------------------------------------

/**
 * Shorten URL
 *
 * Takes a long url and uses the TinyURL API to
 * return a shortened version.
 *
 * Added support for Cyrillic characters.
 *
 * @access    public
 * @param    string    long url
 * @return    string  short url
 */
function shorten_url($url = '')
{
    $CI =& get_instance();

    $CI->load->library('curl');

    if (!$url) {
        $url = site_url($CI->uri->uri_string());
    }

        // If no a protocol in URL, assume its a CI link
    elseif (!preg_match('!^\w+://! i', $url))
    {
        $url = site_url($url);
    }

    return $CI->curl->simple_get('http://tinyurl.com/api-create.php?url=' . $url);
}

function site_url($uri = '')
{
    $Router =& load_class('Router');

    // $uri is expected to be a string, in the form of controller/function/param1
    // trim leading and trailing slashes, just in case
    $uri = trim($uri, '/');

    $routes = $Router->routes;
    $reverseRoutes = array_flip($routes);
    unset($routes['default_controller'], $routes['scaffolding_trigger']);
    $rewrite_enabled = Settings::get('rewrite_enabled');
    // Loop through all routes to check for back-references, then see if the user-supplied URI matches one
    if (preg_match('/admin/i', $uri) || preg_match('/user/i', $uri)) {
        return normal_site_url($uri);
    } else {
        if ($rewrite_enabled == 1) {
            foreach ($routes as $key => $val)
            {
                // bailing if route contains ungrouped regex, otherwise this fails badly
                if (preg_match('/[^\(][.+?{\:]/', $key))
                    continue;

                // Do we have a back-reference?
                if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE) {
                    // Find all back-references in custom route and CI route
                    preg_match_all('/\(.+?\)/', $key, $keyRefs);
                    preg_match_all('/\$.+?/', $val, $valRefs);

                    $keyRefs = $keyRefs[0];

                    // Create URI Regex, to test passed-in uri against a custom route's CI ( standard ) route
                    $uriRegex = $val;

                    // Extract positional parameters (backreferences), and order them such that
                    // the keys of $goodValRefs dirrectly mirror the correct value in $keyRefs
                    $goodValRefs = array();
                    foreach ($valRefs[0] as $ref) {
                        $tempKey = substr($ref, 1);
                        if (is_numeric($tempKey)) {
                            --$tempKey;
                            $goodValRefs[$tempKey] = $ref;
                        }
                    }

                    // Replaces back-references in CI route with custom route's regex [ $1 replaced with (:num), for example ]
                    foreach ($goodValRefs as $tempKey => $ref) {
                        if (isset($keyRefs[$tempKey])) {
                            $uriRegex = str_replace($ref, $keyRefs[$tempKey], $uriRegex);
                        }
                    }

                    // replace :any and :num with .+ and [0-9]+, respectively
                    $uriRegex = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $uriRegex));

                    // regex creation is finished.  Test it against uri
                    if (preg_match('#^' . $uriRegex . '$#', $uri)) {
                        // A match was found.  We can now build the custom URI

                        // We need to create a custom route back-referenced regex, to plug user's uri params into the new routed uri.
                        // First, find all custom route strings between capture groups
                        $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));

                        $routeString = preg_split('/\(.+?\)/', $key);

                        // build regex using original CI route's back-references
                        $replacement = '';
                        $rsEnd = count($routeString) - 1;

                        // merge route strings with original back-references, 1-for-1, like a zipper
                        for ($i = 0; $i < $rsEnd; $i++) {
                            $replacement .= $routeString[$i] . $valRefs[0][$i];
                        }
                        $replacement .= $routeString[$rsEnd];

                        /*
                                   At this point,our variables are defined as:
                                      $uriRegex:		regex to match against user-supplied URI
                                      $replacement:	custom route regex, replacing capture-groups with back-references

                                  All that's left to do is create the custom URI, and return the site_url
                          */
                        $customURI = preg_replace('#^' . $uriRegex . '$#', $replacement, $uri);

                        return normal_site_url($customURI);
                    }
                }
                    // If there is a literal match AND no back-references are setup, and we are done
                else if ($val == $uri)
                    return normal_site_url($key);
            }
        } else {
            return normal_site_url($uri);
        }
    }
}


function normal_site_url($uri = '')
{
    $CI =& get_instance();
    return $CI->config->site_url($uri);
}

?>